package per.kongtouxu.service.Impl;


import org.apache.ibatis.session.RowBounds;
import org.apache.ibatis.session.SqlSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import per.kongtouxu.dao.FileInfoDao;
import per.kongtouxu.domain.pojo.FileInfo;
import per.kongtouxu.domain.pojo.FileType;
import per.kongtouxu.domain.pojo.PageBean;
import per.kongtouxu.domain.pojo.UserScoreIo;
import per.kongtouxu.domain.vo.V_FileInfo;
import per.kongtouxu.service.FileInfoService;
import per.kongtouxu.service.UserScoreIoService;
import per.kongtouxu.service.UserService;

import java.util.List;

@Service
public class FileInfoServiceImpl implements FileInfoService {
    @Autowired
    private FileInfoDao fileInfoDao;
    @Autowired
    private UserService userService;
    @Autowired
    private UserScoreIoService userScoreIoService;
    @Override
    public PageBean<V_FileInfo> pageFind(String FileName, String startTime, String endTime,Integer userId, int currentPage, int pageSize) {
        //1.分页类
        PageBean<V_FileInfo> pageBean = new PageBean<>();
        //2.设置当前页码
        pageBean.setCurrentPage(currentPage);
        //3.设置每页显示条数
        pageBean.setPageSize(pageSize);
        //4.设置总记录条数
        int totalCount = fileInfoDao.findCountFileInfoByPage(FileName,startTime, endTime,userId);
        pageBean.setTotalCount(totalCount);
        //5.设置PageBean中的实体数据
        //开始的记录条数=（当前页码-1）*每页显示条数
        int start = (currentPage - 1) * pageSize;
        List<V_FileInfo> list = fileInfoDao.findFileInfoBypage(FileName,startTime, endTime,userId, new RowBounds(start, pageSize));
        pageBean.setList(list);
        //6.设置总页数   总页数= 总记录条数/每页显示条数=0 ？ 总记录条数/每页显示条数=0 ：（总记录条数/每页显示条数=0）+1
        int totalPage = totalCount % pageSize == 0 ? totalCount / pageSize : (totalCount / pageSize) + 1;
        pageBean.setTotalPage(totalPage);
        //7.返回
        return pageBean;
    }

    @Override
    public FileType findFileTypeBySuffix(String suffix) {
        return fileInfoDao.findFileTypeBySuffix(suffix);
    }

    @Override
    public void add(FileInfo fileInfo ,Integer typeScore) {
        fileInfo.setFileState(0);
        fileInfo.setAdminId(0);
        //上传文件
        fileInfoDao.add(fileInfo);
        //文件上传成功，增加积分 ，添加流水
        System.out.println("添加积分流水"+fileInfo);
        userService.updateScoreByUserId(fileInfo.getUserId(),typeScore);
        System.out.println("userId:"+fileInfo.getUserId()+"分数"+typeScore);
        //添加流水
        UserScoreIo userScoreIo = new UserScoreIo();
        userScoreIo.setFileId(fileInfo.getFileId());
        userScoreIo.setUserId(fileInfo.getUserId());
        userScoreIo.setScore(typeScore);
        userScoreIo.setScoreState("增加");
        userScoreIoService.add(userScoreIo);
    }

    @Override
    public FileInfo findFileById(Integer fileId) {
        return fileInfoDao.findFileById(fileId);
    }
}
